iT邦幫忙

2024 iThome 鐵人賽

DAY 8
0
Modern Web

我阿嬤都會的 kintone 客製化開發系列 第 8

Day 08 | 應用程式搜尋功能(Vue3)

  • 分享至 

  • xImage
  •  

kintone 在應用程式的首頁畫面中有內建搜尋功能,可以透過清單或圖表將搜尋條件定義好,每次就可以點選該清單顯示出篩選後的內容。

但是如果每次要搜尋的內容都不一樣,就要每次再打開清單,輸入搜尋條件後再篩選,過程中要按不少按鈕,稍嫌麻煩。所以這個章節,我們一起來製作在應用程式首頁中的搜尋功能,我們會在上方放入一個 input 的搜尋框,讓使用者可以在這個欄位搜尋自己想要的值。

環境建置

使用我們公司內部開發的工具 create-krsb,快速建立開發環境,所以終端機打上:

npm create krsb

接著選 Vue3,再輸入 .env 的環境變數即可,因為發 API 我習慣用 Axios,所以也順便安裝一下。

應用程式表單

我們放上三個欄位,分別是:客戶姓名、居住縣市、消費金額。

建立按鈕並監聽

打開 ./src/App.vue 並在這支檔案,並撰寫一個搜尋的函式,會用到 Rest API 的 GET 方法:

<script setup>
import axios from 'axios'

// 搜尋所有 records
const search = async () => {
  try {
    const response = await axios.get('/k/v1/records.json', {
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
      },
      params: {
        app: '98' // 目前的應用程式 ID
      }
    })
    console.log(response)
  } catch(e) {
    console.log(e)
  }
}

</script>

<template>
  <div class="content">
    <input type="text" @keypress.enter="search">
  </div>
</template>

如此一來,只要在這個 input 框按下 enter,就會搜尋這個應用程式的所有 record 了。

帶上 query 搜尋

但我們並不是要拿到全部的資料,我們是想要把使用者輸入的值拿來搜尋,所以來建立一個 ref 來存資料,並綁訂在 input:

// script setup 
const inputValue = ref('')

// template
<input v-model="inputValue" type="text" @keypress.enter="search">

再接著把這個值帶到搜尋的函式:

const inputValue = ref('')

const search = async () => {
  try {
    const response = await axios.get('/k/v1/records.json', {
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
      },
      params: {
        app: '98',
        query: `city in ("${inputValue.value}")`
      }
    })
    console.log(response)
  } catch(e) {
    console.log(e)
  }
}

最後的 console.log(response) 就會顯示出我們的資料了。

儲存資料並顯示在畫面

已經可以成功取回資料後,我們再建立一個 ref 來存資料

const records = ref([])

並且把剛剛 API 取回的資料放進去:

records.value = response.data.records

最後渲染到畫面上:

<ul>
  <li v-for="{ name, city } in records">
    <p>{{ name.value }}</p>
    <p>{{ city.value }}</p>
  </li>
</ul>

完整程式碼

<script setup>
import { ref } from 'vue'
import axios from 'axios'

const inputValue = ref('')
const records = ref([])

const search = async () => {
  try {
    const response = await axios.get('/k/v1/records.json', {
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
      },
      params: {
        app: '98',
        query: `city in ("${inputValue.value}")`
      }
    })
    records.value = response.data.records
  } catch(e) {
    console.log(e)
  }
}

</script>

<template>
  <div class="content">
    <input v-model="inputValue" type="text" @keypress.enter="search">
    <ul>
      <li v-for="{ name, city } in records">
        <p>{{ name.value }}</p>
        <p>{{ city.value }}</p>
      </li>
    </ul>
  </div>
</template>


上一篇
Day 07 | kintone 整合 Github Action
下一篇
Day 09 | Kintone UI Component
系列文
我阿嬤都會的 kintone 客製化開發13
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言